<template>
  <div class="step1">
    <header-bar tittle="发布任务"></header-bar>
    <div class="bg"></div>

    <div class="main">
      <div class="step-box">
        <div class="icon-box u-flex-center">
          <div class="icon">
            <van-image
              width="76rem"
              height="76rem"
              :src="require('@/assets/images/step1/icon_1@2x.png')"
            />
            <span>填写任务需求</span>
          </div>

          <div class="line"></div>

          <div class="icon">
            <van-image
              width="76rem"
              height="76rem"
              :src="require('@/assets/images/step1/icon_1@2x.png')"
            />
            <span>设置任务详情</span>
          </div>
        </div>
      </div>

      <div class="card">
        <div class="title">任务需求</div>

        <van-form class="form" @submit="onSubmit">
          <van-field
            class="border"
            v-model="taskLink"
            type="text"
            name="task_link"
            label="任务链接"
            :rules="[{ required: true, message: '请填写任务链接' }]"
            placeholder="任务链接"
          />

          <van-field label="任务描述" disabled />

          <van-field
            class="input border"
            v-model="requirement"
            :clearable="true"
            rows="4"
            label=""
            type="textarea"
            placeholder="请添加任务口令或者任务链接"
            :rules="getLengthRule(requirement)"
          />

          <div class="upload">
            <div class="headerUp">添加验证图</div>
            <div class="uploadCo">
              <div class="icon u-flex-center" v-if="!fileList[0]">
                <van-image
                  width="76rem"
                  height="76rem"
                  :src="require('@/assets/images/step1/icon_photo@2x.png')"
                />
              </div>
              <van-uploader
                :style="fileList[0] ? 'opacity: 1' : 'opacity: 0'"
                v-model="fileList"
                :before-read="beforeRead"
                multiple
                :max-count="1"
              />
            </div>
          </div>
        </van-form>
      </div>

      <div class="btn-box u-flex-center" @click="onSubmit">
        <div class="btn">发布</div>
      </div>
    </div>
  </div>
</template>
<script>
import Vue from "vue";
import { Image as VanImage } from "vant";
import { API_PATH } from "@/api/index.js";
import { TASK_UPLOAD, TASK_All } from "@/api/api.js";
import * as imageConversion from "image-conversion";

import axios from "axios";
import { getLocalStorage } from "@/util/local-storge.js";
import { fliterKind } from "@/util/util.js";
import header from "@/components/header/header.vue";
import {
  Tabbar,
  NoticeBar,
  TabbarItem,
  Search,
  Swipe,
  Uploader,
  SwipeItem,
  Grid,
  GridItem,
  Tab,
  Tabs,
  PullRefresh,
  List,
  Lazyload,
  Sticky,
  Step,
  Steps,
  Form,
  Toast,
} from "vant";
Vue.use(Tabbar);
Vue.use(TabbarItem);
Vue.use(Swipe);
Vue.use(Search);
Vue.use(SwipeItem);
Vue.use(Grid);
Vue.use(GridItem);
Vue.use(Tab);
Vue.use(Tabs);
Vue.use(PullRefresh);
Vue.use(List);
Vue.use(Lazyload);
Vue.use(Sticky);
Vue.use(VanImage);
Vue.use(NoticeBar);
Vue.use(Step);
Vue.use(Steps);
Vue.use(Form);
Vue.use(Uploader);
Vue.use(Toast);
export default {
  name: "step2",
  components: {
    [Tabs.name]: Tabs,
    [Tab.name]: Tab,
    [header.name]: header,
  },
  data() {
    return {
      active: 1,
      getDatas: "",
      requirement: "",
      taskLink: "",
      fileList: [],
    };
  },
  mounted() {
    setTimeout(() => {
      let datas = JSON.parse(decodeURI(this.$route.query.data));
      this.getDatas = datas;
      console.log(datas);
    }, 200);
  },
  methods: {
    // getRule(index) {
    // 	var reg=/^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\/])+$/;
    // 	let str = index.match(/http:\/\/.+/);
    // 	if(!reg.test(index)){
    // 		return [{index, validator: this.validator, message: '请填写合法的链接地址' }];
    // 	}
    // },
    getLengthRule(index) {
      if (index.length < 3) {
        return [
          {
            index,
            validator: this.validator,
            message: "任务描述不得少于3个字节",
          },
        ];
      }
    },
    validator(value, rule) {
      return false;
    },
    onRefresh() {},
    onLoad() {},
    justifyImgWidth(e) {
      console.log(e.currentTarget.clientWidth);
      this.Imgheight = e.currentTarget.clientWidth;
      // this.logoWidth = e.currentTarget.clientHeight * 2.75
    },

    onSubmit(values) {
      // 上传文件
      if (!this.fileList[0]) {
        Toast("请上传图片！");
        return;
      }
      let a = this.fileList[0].file;
      let param = new FormData();
      param.append("file", a);
      let that = this;
      // let file = JSON.parse(JSON.stringify(this.fileList));
      axios
        .post(`${API_PATH + TASK_UPLOAD}`, param, {
          headers: {
            "Content-Type": "multipart/form-data",
            "auth-token": getLocalStorage("user_token").user_token,
          },
        })
        .then(
          function(res) {
            console.log(res);
            if (res.data.status == 1) {
              that.publish(res.data.data.filename);
            }
          },
          function(response) {}
        );

      // this.$router.push({ name: 'step2' });
    },
    async publish(param) {
      const { data } = await this.$reqPost(TASK_All, {
        verify_imgs: param,
        ...this.getDatas,
        requirement: this.requirement,
        task_link: this.taskLink,
      });
      let that = this;
      if (data.status == 1) {
        Toast.success({
          message: data.info,
          onClose: function() {
            that.$router.push("home");
          },
        });
      } else {
        Toast.fail(data.info);
      }
    },
    beforeRead(file) {
      // 上传之前校验
      return new Promise((resolve, reject) => {
        // console.log('压缩前', file) // 压缩到400KB,大于400KB的图片都会进行压缩，小于则不会
        console.log("压缩前", file);
        imageConversion
          .compressAccurately(file, 30)
          .then((res) => {
            // console.log(res)
            res = new File([res], file.name, {
              type: res.type,
              lastModified: Date.now(),
            });
            console.log("压缩后", res);
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
          });
      });
    },
    // 选择分类
    // chooseKind(e) {
    // 	if (e == '3') {
    // 		this.$router.push({ name: 'areaSeckill' });
    // 	}
    // }
  },
};
</script>

<style lang="scss" scoped>
.step1 {
  min-height: 100vh;
  background-color: #f5f5f5;

  .bg {
    height: 464rem;
    background: linear-gradient(
      180deg,
      #2f81fe 80%,
      rgba(47, 129, 254, 0) 100%
    );
  }

  .main {
    position: relative;

    .step-box {
      align-items: flex-end;

      .line {
        width: 300rem;
        height: 8rem;
        background-color: #fff;
      }

      .icon-box {
        margin-top: 42rem;

        .icon {
          position: relative;
          span {
            position: absolute;
            font-size: 24rem;
            width: 144rem;
            left: 50%;
            transform: translate(-50%);
            bottom: -36rem;
            color: #fff;
          }
        }
      }
    }

    .card {
      background-color: #fff;
      border-radius: 20rem;
      overflow: hidden;
      margin: 0 24rem;
      margin-top: 70rem;

      .title {
        padding-left: 24rem;
        font-weight: bold;
        font-size: 32rem;
        text-align: left;
        height: 92rem;
        background-color: #f3f7fe;
        line-height: 92rem;
      }

      .form {
        padding: 0 24rem;

        /deep/ .van-cell__title {
          font-size: 28rem;
          color: #66696e;

          span {
            &::after {
              content: "*";
              color: #ff4343;
              font-size: 28rem;
              margin-left: 8rem;
            }
          }
        }

        /deep/ .van-field__control {
          text-align: right;
        }

        /deep/ .van-field__error-message {
          text-align: right !important;
        }

        /deep/ .van-cell {
          padding: 24rem 0;
        }

        .border {
          border-bottom: 2rem solid #f8f8f8;
        }

        .input {
          /deep/ .van-field__control {
            text-align: left;
          }
        }

        .upload {
          text-align: left;
          padding-bottom: 24rem;

          .headerUp {
            font-size: 28rem;
            margin: 24rem 0;
            color: #66696e;
          }

          .uploadCo {
            position: relative;
            width: 160rem;
            height: 160rem;

            .icon {
              position: absolute;
              width: 160rem;
              height: 160rem;
              border: 2rem dashed #cccfd4;
              border-radius: 12rem;
              background-color: #f6f6f6;
            }
            .van-uploader {
              position: absolute;
              opacity: 1;
              left: 0;
              top: 0;
              opacity: 0;
            }
          }
        }
      }
    }

    .btn-box {
      margin: 80rem 24rem 0;
      border-radius: 44rem;
      height: 88rem;
      background: linear-gradient(145deg, #2cb1ff 0%, #2f81fe 100%);
      font-size: 32rem;
      color: #fff;
      font-weight: bold;

      .btn {
        width: 100%;
      }
    }
  }
}
</style>
